Subprocesses


In [ ]:
from subprocess import (
    call,
    check_call,
    check_output,
    PIPE,
    STDOUT,
    CalledProcessError,
    Popen,
)

Getting return codes


In [ ]:
print call("true")

In [ ]:
print call("false")

In [ ]:
print check_call("false")

In [ ]:
print check_call("fortune")

Not terribly useful. Where is the output going? Let's take a look at the terminal.

Collecting output


In [ ]:
print check_output("fortune")

In [ ]:
command = ["fortune", "--help"]
print check_output(command)

In [ ]:
try:
    print check_output(command)
except CalledProcessError as e:
    print e.output

Where's the error?

Redirection and Communication


In [ ]:
try:
    print check_output(command, stderr=STDOUT)
except CalledProcessError as e:
    print e.output

In [ ]:
lines = """
foo
bar
baz"""

command = ["grep", "-n", "bar"]

e = Popen(command, stdin=PIPE, stdout=PIPE)

stdout, stderr = e.communicate(lines)

print stdout